import router from '@/router'
import { useLoginStore } from '@/stores/loginStore'
import appConstants from '@/utils/appConstants'
import axios from 'axios'
import { Toast } from 'vant'
import lodash from 'lodash'

const instance = axios.create({
  timeout: 10000,
  baseURL: import.meta.env.VITE_API_BASE_URL,
})

instance.interceptors.request.use(
  function (config) {
    const loginStore = useLoginStore()
    const token = lodash.get(loginStore, 'loginInfo.token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  },
)

instance.interceptors.response.use(
  function (response) {
    if (lodash.get(response, 'data.data.status') !== appConstants.success) {
      return Promise.reject(response.data)
    }
    const newToken = response.headers['x-new-token']
    if (newToken) {
      const loginStore = useLoginStore()
      loginStore.setLoginInfo({
        ...loginStore.loginInfo,
        token: newToken,
      })
    }
    return response.data
  },
  function (error) {
    const loginStore = useLoginStore()
    if (error.response) {
      switch (error.response.status) {
        case 401:
          loginStore.clearLoginInfo()
          Toast.fail('请登录后操作')
          router.push('/login')
          break
        case 403:
          // 处理 403 禁止访问
          Toast.fail('抱歉，您没有权限访问该资源')
          break
        case 404:
          Toast.fail('抱歉，您访问的资源不存在')
          // 处理 404 未找到
          break
        // 其他状态码处理
        default:
          Toast.fail('抱歉，出现未知错误')
          console.error('An error occurred:', error.response.status, error.response.data)
      }
    } else {
      // 处理网络错误
      Toast.fail('抱歉，出现网络错误')
      console.error('Network Error:', error.message)
    }
    return Promise.reject(error)
  },
)

export default instance
